package com.zy.core.common.security.filter;

import com.zy.core.common.security.util.ShiroUtils;
import com.zy.core.common.utils.StringUtils;
import com.zy.project.system.user.entity.SystemUser;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 注销过滤器
 * Package: core.web.filter
 * <p>
 * Description： TODO
 * <p>
 * Author: zhangyu
 * <p>
 * Date: Created in 2018-9-22 20:55
 * <p>
 * Company: mingtu
 * <p>
 * Copyright: Copyright (c) 2018
 * <p>
 * Version: 0.0.1
 * <p>
 * Modified By:
 */
public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter {
    private static final Logger log = LoggerFactory.getLogger(LogoutFilter.class);

    /**
     * 退出后重定向的地址
     */
    private String loginUrl;

    public String getLoginUrl(){
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl){
        this.loginUrl = loginUrl;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception{
        try
        {
            Subject subject = getSubject(request, response);
            String redirectUrl = getRedirectUrl(request, response, subject);
            try{
                SystemUser user = ShiroUtils.getUser();
                String sessionId = ShiroUtils.getSessionId();
                if (StringUtils.isNotNull(user)){
                    //String loginName = user.getLoginName();
                    // 记录用户退出日志
                    //AsyncUtil.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
                }
                // 退出登录
                subject.logout();
                //log.info("用户" + );
            }
            catch (SessionException ise){
                log.error("logout fail.", ise);
            }
            issueRedirect(request, response, redirectUrl);
        }
        catch (Exception e){
            log.error("Encountered session exception during logout.  This can generally safely be ignored.", e);
        }
        return false;
    }

    /**
     * 退出跳转URL
     */
    @Override
    protected String getRedirectUrl(ServletRequest request, ServletResponse response, Subject subject){
        String url = getLoginUrl();
        if (StringUtils.isNotEmpty(url)){
            return url;
        }
        return super.getRedirectUrl(request, response, subject);
    }
}
